﻿using Ivi.Visa;
using NationalInstruments.Visa;
using TCommon;
using TCommunication.Common;

namespace TCommunication.Impl;

public class VisaSerialCommunication:VisaCommunication
{
    public string PortName
    {
        get
        {
            var result = VisaHelper.ResourceNameConverterToSerialPortName(ResourceName);
            if (result.IsSuccess)
            {
                return result.Content!;
            }
            else
            {
                return string.Empty;
            }
        }
        set
        {
            var result = VisaHelper.SerialPortNameConvertToVisaResourceName(value);
            if (result.IsSuccess)
            {
                ResourceName = result.Content!;
            }
        }
    }
    public int BaudRate { get; set; }

    public override OperateResult Connect()
    {
        if (IsConnected)
        {
            return OperateResult.CreateSuccessResult();
        }
        var result = base.Connect();
        if (result.IsSuccess)
        {
            if (Session is SerialSession serialSession)
            {
                serialSession.BaudRate = BaudRate;
                serialSession.DataBits = 8;
                serialSession.Parity = SerialParity.None;
                serialSession.FlowControl = SerialFlowControlModes.DtrDsr;
                return OperateResult.CreateSuccessResult();
            }
            else
            {
                Session?.Dispose();
                return OperateResult.CreateFailedResult("当前资源名非串口资源");
            }
        }
        else
        {
            return result;
        }
    }
}